package com.hw.paltfrom.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;

import java.time.LocalTime;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.hw.paltfrom.rescode.HWSystemCode;
import com.hw.paltfrom.utils.*;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.hw.paltfrom.mongoDto.ActionLog;


//用于单个用户不能同时多个设备在线

@Component
public class OverFilter implements Filter {

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("《-----全局拦截器启动-------》");
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {
//		ServletRequest requestWrapper = null;
//		if (servletRequest instanceof HttpServletRequest) {
//			requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) servletRequest);
//		}
		// 设置字符集和对象封装
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
//		request = new BodyReaderHttpServletRequestWrapper(request);
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		
		
		
		String path = request.getRequestURI();
		// //行为日志记录
		// actionLog(requestWrapper, servletResponse);

		//跨域
		accessAllowOrigin(request,response);

		//全部放行
//		chain.doFilter(servletRequest, servletResponse);
		chain.doFilter(request, response);

		// 登陆校验
		/*if (path.contains("/user/login")) {//放行登录请求
			chain.doFilter(servletRequest, servletResponse);
		}else {
		    //登录失败
			boolean loginVerf = loginVerf(request,response);
			if (loginVerf) {
				chain.doFilter(servletRequest, servletResponse);
			} else {
				PrintWriter writer = null;
				try {
					writer = servletResponse.getWriter();
					JSONObject js = new JSONObject();
					js.put("code", HWSystemCode.NOT_LOGIN.code());
					js.put("msg", HWSystemCode.NOT_LOGIN.msg());
					writer.print(js.toJSONString());
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (writer != null)
						writer.close();
				}
			}
		}*/
//
//		 校验是否登陆
//
		 //权限验证
//		 boolean auth = auth(requestWrapper);
//		 if (auth) {
//		 chain.doFilter(requestWrapper, servletResponse);
//		 } else {
//		 PrintWriter writer = null;
//		 try {
//		 writer = servletResponse.getWriter();
//		 JSONObject js = new JSONObject();
//		 js.put("code", HWSystemCode.AUTHFAIL.code());
//		 js.put("msg", HWSystemCode.AUTHFAIL.msg());
//		 writer.print(js.toJSONString());
//		 } catch (Exception e) {
//		 e.printStackTrace();
//		 } finally {
//		 if (writer != null)
//		 writer.close();
//		 }
//		 }

	}

	@Override
	public void destroy() {

	}

	// 行为日志
	@SuppressWarnings("unused")
	private void actionLog(ServletRequest servletRequest, ServletResponse servletResponse) {

		MongodbUtil mongodbUtil = SpringUtil.getBean(MongodbUtil.class);
		ActionLog aLog = new ActionLog();
		String userid = servletRequest.getParameter("userID");
		String actionName = servletRequest.getParameter("actionName");
		String F_ModuleId = servletRequest.getParameter("F_ModuleId");

		aLog.setId(RandomNumberUtil.getCode());
		aLog.setTokenID("action" + userid);
		aLog.setActionName(actionName);
		aLog.setDate(LocalTime.now());
		aLog.setF_ModuleId(F_ModuleId);
		mongodbUtil.insert(aLog);
	}

	// 校验登陆状态
	/*private boolean loginVerf(HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
		RedisUtil redis = SpringUtil.getBean(RedisUtil.class);
//        Map<String, String> cookieMap = CookieUtil.readCookie((HttpServletRequest) servletRequest, "token");
//        String t = cookieMap.get("token");
		//从headers里获取fAccount和token
		String  fAccount = "";
		fAccount = servletRequest.getHeader("fAccount");
		String token = "";
		if (StringUtils.isNotBlank(servletRequest.getHeader("token"))) {
			token = servletRequest.getHeader("token");
		}
//		String fAccount = servletRequest.getParameter("fAccount");
//		String token = servletRequest.getParameter("token");
		//将前端传输token与redis中缓存的token进行比对
		String object = null;
		try {
			object = (String)redis.get("loginToken:"+fAccount);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return token.equals(object);
	}*/

	// 权限验证
	@SuppressWarnings("unused")
	private boolean auth(ServletRequest request) {
		RedisUtil redis = SpringUtil.getBean(RedisUtil.class);

		String userID = request.getParameter("userID");
		// 当前请求的页面id
		String F_ModuleId = request.getParameter("F_ModuleId");
		// 查询权限缓存，看当前页面id是否存在

		Object object = redis.get("auth" + userID);
		List<Object> list = Arrays.asList(object);
		boolean contains = list.contains(F_ModuleId);
		return contains;

	}

	//	请求字节流
	private void accessAllowOrigin(HttpServletRequest request,HttpServletResponse response){
		// 响应标头指定 指定可以访问资源的URI路径
		response.setHeader("Access-Control-Allow-Origin", "*");


		//响应标头指定响应访问所述资源到时允许的一种或多种方法
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");

		//设置 缓存可以生存的最大秒数
		response.setHeader("Access-Control-Max-Age", "3600");

		//设置  受支持请求标头（自定义  可以访问的请求头  例如：Token）
		response.setHeader("Access-Control-Allow-Headers", "content-type,x-requested-with,Authorization,DNT,User-Agent,Keep-Alive,accept,origin,Access-Control-Allow-Headers,Content-Length,x-ui-request,lang");

		//自定义 可以被访问的响应头
		response.setHeader("Access-Control-Expose-Headers","checkTokenResult");

		// 指示的请求的响应是否可以暴露于该页面。当true值返回时它可以被暴露
		response.setHeader("Access-Control-Allow-Credentials","true");
		if (request.getMethod().equals("OPTIONS")) {
			response.setStatus(HttpStatus.SC_OK);
			try {
				response.getWriter().write("OPTIONS returns OK");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return;
		}


	}
	// private String readJsonFromRequestBody(ServletRequest stream) {
	// String jsonData = "";
	// try {
	// BufferedReader reader = stream.getReader();
	// StringBuffer buffer = new StringBuffer("");
	//
	// String temp;
	// while ((temp = reader.readLine()) != null) {
	// buffer.append(temp);
	// }
	//
	// reader.close();
	// jsonData = buffer.toString();
	//
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	//
	// return jsonData;
	// }

}
